﻿using System;
using System.Text;
using System.Xml.Linq;

namespace WebQuestionnaire.Core.Parsers
{
    using System;
    using System.Collections.Generic;
    using System.Xml;
    using System.Linq;
    
    /// <summary>
    /// Parse Xmldocument stored in DB as string
    /// </summary>
    public class AnswersParser
    {
        private XDocument document;

        public AnswersParser(string answers)
        {
        
            if (!String.IsNullOrEmpty(answers))
            {
                document=XDocument.Parse(answers);
            }
            else
            {
                CreateEmptyAnswers();
            }
        }

        public void CreateEmptyAnswers()
        {
            document=new XDocument(new XDeclaration("1.0", Encoding.UTF8.HeaderName, String.Empty),new XElement("Answers"));
        }

        /// <summary>
        /// transform xmlDocument to list of Answers
        /// </summary>
        /// <returns>list of answers</returns>
        public List<string> GetAnswers()
        {
            List<string> answers = (document.Descendants("Answer").Select(i => i.Attribute("text").Value)).ToList();
            return answers;
        }

        /// <summary>
        /// Insert answer to xmlDocument
        /// </summary>
        /// <param name="answer">answer to insert</param>
        public void AddAnswer(string answer)
        {
            document.Element("Answers").Add(new XElement("Answer",new XAttribute("text",answer)));
        }

        /// <summary>
        /// Remove answer from xmlDocument
        /// </summary>
        /// <param name="answer">answer to remove</param>
        public void RemoveAnswer(string answer)
        {
            document.Descendants("Answer").Where(x => (string)x.Attribute("text") == answer).Remove();
        }

        /// <summary>
        /// Transorm xmlDocument to string
        /// </summary>
        /// <returns>transformed document</returns>
        public override string ToString()
        {
            return document.ToString();
        }
    }
}
